package com.xw.roomWeb.web;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.xw.roomWeb.enums.ResultCodeEnum;
import com.xw.roomWeb.service.UserInfoService;
import com.xw.roomWeb.vo.ResultDto;
import com.xw.roomWeb.vo.request.UserInfoRequestDTO;
import com.xw.roomWeb.vo.response.UserInfoResponseDTO;

@Controller
public class TestController {

	@Autowired
	private Producer captchaProducer = null;

	@Autowired
	private UserInfoService userInfoService;

	@RequestMapping(value = "/login")
	public String login(Model model) {

		return "login";
	}

	@RequestMapping("/captcha-image")
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setDateHeader("Expires", 0);// 禁止服务器端缓存
		// 设置标准的 HTTP/1.1 no-cache headers.
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		// 设置IE扩展 HTTP/1.1 no-cache headers (use addHeader).
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");// 设置标准 HTTP/1.0 不缓存图片
		response.setContentType("image/jpeg");// 返回一个 jpeg 图片，默认是text/html(输出文档的MIMI类型)
		String capText = captchaProducer.createText();// 为图片创建文本

		// 将文本保存在session中，这里就使用包中的静态变量吧
		request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

		BufferedImage bi = captchaProducer.createImage(capText); // 创建带有文本的图片
		ServletOutputStream out = response.getOutputStream();
		// 图片数据输出
		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}

		System.out.println("Session 验证码是：" + request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY));
		return null;
	}

	@RequestMapping(value = "/index")
	public String index(Model model, HttpServletRequest request) {
		UserInfoRequestDTO userInfoRequestDTO = new UserInfoRequestDTO();
		userInfoRequestDTO.setUserId(73L);
		ResultDto<UserInfoResponseDTO> resultDto  =this.userInfoService.loadById(userInfoRequestDTO);
		if (resultDto.getCode().equals(ResultCodeEnum.System.SUCCESS.getCode())) {
			UserInfoResponseDTO responseVO= resultDto.getObject();
			model.addAttribute("userInfoVo", responseVO);
		}
		
		return "index";
	}
}
